package tamz2.fuellog;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

public class Database {

	private static final String TABLE_NAME = "table1";
		 
	private Context context;
	private SQLiteDatabase db;
		 
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into "
		      + TABLE_NAME + "(name, day, month, year, ftype, tach) values (?, ?, ?, ?, ?, ?)";
		 
	private Cursor c;
	
	public Record getFirst() {
		  c = this.db.query(TABLE_NAME, new String[] { "name", "day", "month", "year", "ftype", "tach", },
			        null, null, null, null, "name desc");
		  
		  if (c.moveToFirst())
			  return (new Record(c.getString(0), c.getInt(1), c.getInt(2), c.getInt(3), c.getInt(4), c.getInt(5)));
		  
		  return null;
	}
	
	public Record getNext() {
		if (c.moveToNext())
			return (new Record(c.getString(0), c.getInt(1), c.getInt(2), c.getInt(3), c.getInt(4), c.getInt(5)));
		  
		  return null;
	}
	
	public Record getPrev() {
		if (c.moveToPrevious())
			return (new Record(c.getString(0), c.getInt(1), c.getInt(2), c.getInt(3), c.getInt(4), c.getInt(5)));
		  
		  return null;
		
		
	}
	
	public Database(Context context) {
		this.context = context;
		DatabaseHelper openHelper = new DatabaseHelper(this.context);
	    this.db = openHelper.getWritableDatabase();
	    this.insertStmt = this.db.compileStatement(INSERT);
	}
		 
	public long insert(String name, int day, int month, int year, int ftype, int tach) {
	      this.insertStmt.bindString(1, name);
	      this.insertStmt.bindLong(2, day);
	      this.insertStmt.bindLong(3, month);
	      this.insertStmt.bindLong(4, year);
	      this.insertStmt.bindLong(5, ftype);
	      this.insertStmt.bindLong(6, tach);
	      return this.insertStmt.executeInsert();
	}
		 
	public void deleteAll() {
	      this.db.delete(TABLE_NAME, null, null);
	}
		 
	public List<Record> selectAll() {
	      List<Record> list = new ArrayList<Record>();
	      Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name", "day", "month", "year", "ftype", "tach", },
	  			
		        null, null, null, null, "name desc");
		      if (cursor.moveToFirst()) {
		         do {
		            list.add(cursor.getString(0));
		         } while (cursor.moveToNext());
		      }
		      if (cursor != null && !cursor.isClosed()) {
		         cursor.close();
		      }
		      return list;
	}
		 
	
	
	
}
